package com.zsc.wxm.ysh.anjo.oss.controller;

import com.zsc.wxm.ysh.anjo.oss.service.FileService;
import com.zsc.wxm.ysh.anjo.result.CodeEnum;
import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.service.base.exception.AnjoException;
import com.zsc.wxm.ysh.anjo.utils.ExceptionUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HP
 */
@RestController
@RequestMapping("/oss/file")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){
        try {
            log.info("调用oss服务upload()方法...");
            String url = fileService.upload(file);
            Map<String, Object> data = new HashMap<>();
            data.put("url", url);
            return Result.ok("上传成功", data);
        } catch (IOException e) {
            log.error("-----文件上传发生错误----" + ExceptionUtil.getMessage(e));
            throw new AnjoException(CodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @DeleteMapping("/remove")
    public Result remove(@RequestParam("url") String url){
        try {
            log.info("调用oss服务remove()方法...");
            fileService.removeImage(url);
            return Result.ok("文件移除成功");
        } catch (Exception e) {
            log.error("-----文件删除发生错误----" + ExceptionUtil.getMessage(e));
            throw new AnjoException(CodeEnum.FILE_REMOVE_ERROR);
        }

    }

    @PostMapping("/upload-house-image")
    @ApiOperation("上传爬虫爬取的图片到oss中")
    public Result uploadHouseImage() {
        try {
            fileService.uploadHouseImage();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("成功");
    }

}
